/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.service.loader;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.Validate;
import org.jrose.core.util.AnnotationUtils;
import org.jrose.core.util.XMLUtils;
import org.w3c.dom.Element;

import java.io.Serializable;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.LinkedList;
import java.util.List;

/**
 * Abstract standard configuration loader implementation.
 *
 * @author Xiaohai Zhang
 * @since 2013-08-25 14:59
 */
@NoArgsConstructor(access = AccessLevel.PROTECTED)
abstract public class AbstractStandardConfigurationLoader<E extends Serializable> extends AbstractConfigurationLoader<E> {
    @Documented
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    public static @interface StandardConfiguration {
        String value();
    }

    @Override
    final protected List<E> parseDocument(Element root) {
        StandardConfiguration standardConfiguration = AnnotationUtils.getAnnotation(getClass(), StandardConfiguration.class);
        Validate.notNull(standardConfiguration, "No @StandardConfiguration annotated on '%s'", getClass().getName());
        List<E> configurations = new LinkedList<>();
        for (Element element : XMLUtils.getChildElements(root, standardConfiguration.value())) {
            E configuration = parseElement(element);
            Validate.notNull(configuration);
            configurations.add(configuration);
        }
        return configurations;
    }

    abstract protected E parseElement(Element element);
}
